import 'package:json_annotation/json_annotation.dart';

part 'order.g.dart';

@JsonSerializable()
class OrderItem {
  final String id;
  final String name;
  final double price;
  final int quantity;

  OrderItem({
    required this.id,
    required this.name,
    required this.price,
    required this.quantity,
  });

  factory OrderItem.fromJson(Map<String, dynamic> json) => _$OrderItemFromJson(json);
  Map<String, dynamic> toJson() => _$OrderItemToJson(this);
}

@JsonSerializable()
class Order {
  final String id;
  final String userId;
  final List<OrderItem> items;
  late final double total;
  late final String status;
  @JsonKey(name: 'created_at')
  final DateTime createdAt;
  @JsonKey(name: 'updated_at')
  late final DateTime updatedAt;

  Order({
    required this.id,
    required this.userId,
    required this.items,
    required this.total,
    this.status = 'pending',
    required this.createdAt,
    required this.updatedAt,
  });

  factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json);
  Map<String, dynamic> toJson() => _$OrderToJson(this);

  // 计算总金额
  double calculateTotal() {
    return items.fold(0.0, (sum, item) => sum + (item.price * item.quantity));
  }

  // 添加订单项
  void addItem(OrderItem item) {
    items.add(item);
    total = calculateTotal();
    updatedAt = DateTime.now();
  }

  // 移除订单项
  void removeItem(String itemId) {
    items.removeWhere((item) => item.id == itemId);
    total = calculateTotal();
    updatedAt = DateTime.now();
  }

  // 更新订单状态
  void updateStatus(String newStatus) {
    status = newStatus;
    updatedAt = DateTime.now();
  }

  // 获取订单摘要
  String get summary {
    return 'Order #$id: ${items.length} items, Total: \$${total.toStringAsFixed(2)}';
  }
}

// 订单状态枚举
enum OrderStatus {
  pending('Pending'),
  processing('Processing'),
  shipped('Shipped'),
  delivered('Delivered'),
  cancelled('Cancelled');

  final String displayName;
  const OrderStatus(this.displayName);

  static OrderStatus fromString(String value) {
    return values.firstWhere(
          (e) => e.toString().split('.').last == value,
      orElse: () => OrderStatus.pending,
    );
  }
}